import React, { Component } from 'react';
import PubSub from 'pubsub-js'
import Item from '../Item';

class List extends Component {

  // 初始化状态
  state = {
    userArr:[],  // 用户信息列表
    isFirst:true,  // 是否为初次进入页面
    isLoading:false,  // 是否为加载状态
    err:'',  // 报错信息
  }

  componentDidMount(){
    // 订阅消息
    this.token = PubSub.subscribe('users', (_, stateObj)=>{
      console.log(stateObj)
      this.setState(stateObj)
    })
  }

  componentWillUnmount(){
    // 取消订阅
    PubSub.unsubscribe(this.token)
  }

  render() {
    const {userArr, err, isFirst, isLoading} = this.state
    return (
      <div className='row'>
        {
          isFirst ? <h3>Enter name to search</h3> :
          isLoading ? <h3>Loading....</h3> :
          err ? <h3 style={{color:'red'}}>{ err }</h3> :
          userArr.map((user)=>{
            return <Item key={user.id} {...user}/>
          })
        }
      </div>
    );
  }
}

export default List;